package com.sinodata.bsm.cicp.util.pool;

import java.net.HttpURLConnection;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.pool.ObjectPool;
import org.apache.commons.pool.impl.GenericObjectPool;
import org.apache.log4j.Logger;

/**
 * <p>
 * Description: 
 * </p>
 *
 * @author wangpeng
 * @version 1.0

 * <p>
 * History: 
 *
 * Date                     Author         Version     Description
 * ---------------------------------------------------------------------------------
 * 2012-12-12 PM 4:54:20    wangpeng       1.0         To create
 * 
 * </p>
 *
 * @since 
 * @see     
 */
public class URLConnPool {
    private static final Logger logger = Logger.getLogger("urllog");
    private final Map<String, ObjectPool> map = new HashMap<String, ObjectPool>();
    private static URLConnPool instance = null;
    private final Object _lock = new Object();

    private URLConnPool() {

    }

    public synchronized static URLConnPool getInstance() {
        if (instance == null) {
            instance = new URLConnPool();
        }
        return instance;
    }

    public HttpURLConnection getConnection(String urlStr, int maxSize, int outTime) throws Exception {
        ObjectPool pool = map.get(urlStr);
        if (pool == null) {
            synchronized (_lock) {
                pool = map.get(urlStr);
                if (pool == null) {
                    URLPoolableObject factory = new URLPoolableObject(urlStr);
                    GenericObjectPool.Config config = new GenericObjectPool.Config();
                    config.lifo = false;
                    config.maxActive = maxSize;
                    config.maxIdle = maxSize;
                    config.whenExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_BLOCK;
                    config.minIdle = 0;
                    config.testOnReturn = true;
                    //config.testOnBorrow = true;
                    config.maxWait = outTime;
                    pool = new GenericObjectPool(factory, config);
                    map.put(urlStr, pool);
                }
            }
        }
        logger.info("现在活动的url连接数量： " + pool.getNumActive() + " 现在空闲的url连接数量：" + pool.getNumIdle());
        return (HttpURLConnection) pool.borrowObject();
    }

    public void updateURL(String urlStr) {
        ObjectPool pool = map.get(urlStr);
        try {
            pool.close();
            map.put(urlStr, null);
        } catch (Exception e) {
            logger.error(e);
        }
    }

    /**
     * 释放一个连接  如果此连接有效 则放入连接池 如果无效 则关闭
     * @param urlStr
     * @param connection
     */
    public void relase(String urlStr, HttpURLConnection connection) {
        ObjectPool pool = map.get(urlStr);
        try {
            if (connection == null) {
                return;
            }
            pool.returnObject(connection);
        } catch (Exception e) {
            logger.error(e);
        }
    }
}
